package com.ehome.poct.backend.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONUtil;
import com.ehome.poct.backend.api.VersonInfoDTO;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

public class EzipUtil {

    public static VersonInfoDTO unzipJson(MultipartFile file){
        String url = EzipUtil.class.getResource("/").getPath().concat(UUID.fastUUID().toString());
        try {
            File unzip = ZipUtil.unzip(file.getInputStream(), new File(url), Charset.defaultCharset());
            List<File> files = FileUtil.loopFiles(unzip, f -> {
                String extName = FileUtil.extName(f);
                return "json".equals(extName);
            });
            for (File file1 : files) {
                FileReader fileReader = new FileReader(file1);
                String s = fileReader.readString();
                boolean json = JSONUtil.isJson(s);
                if(json){
                    return JSONUtil.toBean(s,VersonInfoDTO.class);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            FileUtil.del(url);
        }
        return null;
    }
    
    public static File unzip(MultipartFile file){
        String url = EzipUtil.class.getResource("/").getPath().concat(UUID.fastUUID().toString());
        try {
            File unzip = ZipUtil.unzip(file.getInputStream(), new File(url), Charset.defaultCharset());
            List<File> files = FileUtil.loopFiles(unzip, f -> {
                String extName = FileUtil.extName(f);
                return !"json".equals(extName);
            });
            return files.get(0);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /*public static File zip(List<File> file,String name){
        String url = EzipUtil.class.getResource("/").getPath().concat(UUID.fastUUID().toString()).concat("/").concat(name);
        File file2 = FileUtil.file(url);
        Archiver archiver = CompressUtil.createArchiver(CharsetUtil.CHARSET_UTF_8, ArchiveStreamFactory.ZIP, file2);
        for (File file1 : file) {
            archiver.add(file1);
        }
        archiver.finish().close();
        return file2;
    }*/
}
